<template>
  <view class="edit-page menu-edit-page">
    <!-- 表单内容 -->
    <view class="form-content">
      <uni-forms
          ref="formRef"
          :model="formData"
          :rules="formRules"
          label-width="100px">

        <uni-forms-item label="上级菜单" name="parentId">
          <BottomTreeSelect
              v-model="formData.parentId"
              :tree-data="parentMenuTreeData"
              value-field="menuId"
              label-field="menuName"
              children-field="children"
              placeholder="请选择上级菜单"
              title="选择上级菜单"
              :disabled="isDisabled">
          </BottomTreeSelect>
        </uni-forms-item>

        <uni-forms-item label="菜单类型" name="menuType" required>
          <BottomSelect
              v-model="formData.menuType"
              :options="menuTypeOptions"
              value-field="value"
              label-field="text"
              placeholder="请选择菜单类型"
              title="选择菜单类型"
              :disabled="isDisabled">
          </BottomSelect>
        </uni-forms-item>

        <uni-forms-item label="菜单名称" name="menuName" required>
          <uni-easyinput
              v-model="formData.menuName"
              placeholder="请输入菜单名称"
              :clearable="true"
              :disabled="isDisabled">
          </uni-easyinput>
        </uni-forms-item>

        <uni-forms-item label="显示排序" name="orderNum">
          <uni-easyinput
              v-model="formData.orderNum"
              type="number"
              placeholder="请输入显示排序"
              :disabled="isDisabled">
          </uni-easyinput>
        </uni-forms-item>

        <uni-forms-item label="路由地址" name="path" v-if="formData.menuType !== 'F'">
          <uni-easyinput
              v-model="formData.path"
              placeholder="请输入路由地址"
              :clearable="true"
              :disabled="isDisabled">
          </uni-easyinput>
        </uni-forms-item>

        <uni-forms-item label="权限字符" name="perms">
          <uni-easyinput
              v-model="formData.perms"
              placeholder="请输入权限字符"
              :clearable="true"
              :disabled="isDisabled">
          </uni-easyinput>
        </uni-forms-item>

        <uni-forms-item label="菜单图标" name="icon" v-if="formData.menuType !== 'F'">
          <uni-easyinput
              v-model="formData.icon"
              placeholder="请输入菜单图标"
              :clearable="true"
              :disabled="isDisabled">
          </uni-easyinput>
        </uni-forms-item>

        <uni-forms-item label="APP图标" name="appIcon" v-if="formData.menuType === 'C'">
          <uni-easyinput
              v-model="formData.appIcon"
              placeholder="请输入APP图标名称"
              :clearable="true"
              :disabled="isDisabled">
            <template #right>
              <uni-icons v-if="formData.appIcon" :type="formData.appIcon" size="20"
                         :color="formData.appColor || '#409EFF'"/>
            </template>
          </uni-easyinput>
        </uni-forms-item>

        <uni-forms-item label="APP颜色" name="appColor" v-if="formData.menuType === 'C'">
          <view class="color-picker-wrapper" @click="isDisabled ? null : openColorPicker">
            <uni-easyinput
                v-model="formData.appColor"
                placeholder="请选择颜色"
                readonly
                :clearable="true"
                :disabled="isDisabled"
                @clear="clearColor">
              <template #right>
                <view class="color-preview-large" :style="{ backgroundColor: formData.appColor || '#409EFF' }"></view>
              </template>
            </uni-easyinput>
          </view>
        </uni-forms-item>

        <uni-forms-item label="是否显示" name="visible">
          <BottomSelect
              v-model="formData.visible"
              :options="visibleOptions"
              value-field="value"
              label-field="text"
              placeholder="请选择是否显示"
              title="选择是否显示"
              :disabled="isDisabled">
          </BottomSelect>
        </uni-forms-item>

        <uni-forms-item label="菜单状态" name="status">
          <BottomSelect
              v-model="formData.status"
              :options="statusOptions"
              value-field="value"
              label-field="text"
              placeholder="请选择菜单状态"
              title="选择菜单状态"
              :disabled="isDisabled">
          </BottomSelect>
        </uni-forms-item>

        <uni-forms-item label="是否外链" name="isFrame" v-if="formData.menuType === 'C'">
          <BottomSelect
              v-model="formData.isFrame"
              :options="frameOptions"
              value-field="value"
              label-field="text"
              placeholder="请选择是否外链"
              title="选择是否外链"
              :disabled="isDisabled">
          </BottomSelect>
        </uni-forms-item>

        <uni-forms-item label="是否缓存" name="isCache" v-if="formData.menuType === 'C'">
          <BottomSelect
              v-model="formData.isCache"
              :options="cacheOptions"
              value-field="value"
              label-field="text"
              placeholder="请选择是否缓存"
              title="选择是否缓存"
              :disabled="isDisabled">
          </BottomSelect>
        </uni-forms-item>

        <uni-forms-item label="菜单备注" name="remark">
          <uni-easyinput
              v-model="formData.remark"
              type="textarea"
              placeholder="请输入菜单备注"
              :maxlength="200"
              :disabled="isDisabled">
          </uni-easyinput>
        </uni-forms-item>
      </uni-forms>

    </view>

    <!-- 底部操作按钮 -->
    <view class="footer-actions">
      <view class="action-buttons">
        <view
            v-if="mode !== 'view'"
            class="cancel-btn"
            @click="handleBack">
          取消
        </view>
        <view
            v-if="mode !== 'view'"
            class="submit-btn"
            @click="handleSubmit">
          {{ mode === 'add' ? '确认新增' : '保存修改' }}
        </view>
      </view>
    </view>

    <!-- 颜色选择器 -->
    <t-color-picker
        ref="colorPicker"
        :color="colorPickerColor"
        :spareColor="spareColors"
        @confirm="onColorConfirm"
    />
  </view>
</template>

<script setup>
import {computed, getCurrentInstance, onMounted, reactive, ref} from 'vue'
import {onLoad} from '@dcloudio/uni-app'
import {addMenu, getMenu, listMenu, updateMenu} from '@/api/system/menu'
import tColorPicker from '@/components/t-color-picker/t-color-picker.vue'
import {BottomSelect, BottomTreeSelect} from '@/components/select'
import {handleTree} from '@/utils/ruoyi'

const {proxy} = getCurrentInstance()

// 页面参数
const mode = ref('add') // add, edit, view
const menuId = ref('')
const parentId = ref('')

// 表单引用
const formRef = ref()
const colorPicker = ref()

// 表单数据
const formData = reactive({
  parentId: 0,
  menuType: 'M',
  menuName: '',
  orderNum: 0,
  path: '',
  perms: '',
  icon: '',
  appIcon: '',
  appColor: '',
  visible: '0',
  status: '0',
  isFrame: '1',
  isCache: '0',
  remark: ''
})

// 表单验证规则
const formRules = {
  menuName: {
    rules: [
      {required: true, errorMessage: '请输入菜单名称'}
    ]
  },
  menuType: {
    rules: [
      {required: true, errorMessage: '请选择菜单类型'}
    ]
  }
}

// 选项数据
const menuTypeOptions = [
  {value: 'M', text: '目录'},
  {value: 'C', text: '菜单'},
  {value: 'F', text: '按钮'}
]

const visibleOptions = [
  {value: '0', text: '显示'},
  {value: '1', text: '隐藏'}
]

const statusOptions = [
  {value: '0', text: '正常'},
  {value: '1', text: '停用'}
]

const frameOptions = [
  {value: '1', text: '是'},
  {value: '0', text: '否'}
]

const cacheOptions = [
  {value: '0', text: '缓存'},
  {value: '1', text: '不缓存'}
]

const parentMenuTreeData = ref([])

// 颜色选择器相关
const colorPickerColor = ref({r: 64, g: 158, b: 255, a: 1}) // 默认蓝色
const spareColors = ref([
  {r: 24, g: 144, b: 255, a: 1},   // #1890ff
  {r: 82, g: 196, b: 26, a: 1},    // #52c41a
  {r: 250, g: 173, b: 20, a: 1},   // #faad14
  {r: 19, g: 194, b: 194, a: 1},   // #13c2c2
  {r: 114, g: 46, b: 209, a: 1},   // #722ed1
  {r: 235, g: 47, b: 150, a: 1},   // #eb2f96
  {r: 245, g: 34, b: 45, a: 1},    // #f5222d
  {r: 250, g: 140, b: 22, a: 1},   // #fa8c16
  {r: 64, g: 158, b: 255, a: 1},   // #409EFF
  {r: 103, g: 194, b: 58, a: 1},   // #67C23A
  {r: 230, g: 162, b: 60, a: 1},   // #E6A23C
  {r: 245, g: 108, b: 108, a: 1},  // #F56C6C
])

// 页面标题
const pageTitle = computed(() => {
  switch (mode.value) {
    case 'add':
      return '新增菜单'
    case 'edit':
      return '编辑菜单'
    case 'view':
      return '查看菜单'
    default:
      return '菜单管理'
  }
})

// 是否禁用表单
const isDisabled = computed(() => {
  return mode.value === 'view'
})

// 页面加载
// ==================== 修复：使用 onLoad 生命周期钩子 ====================
onLoad((options) => {

  mode.value = options.mode || 'add'
  menuId.value = options.menuId || ''
  parentId.value = options.parentId || ''

  // 设置父级菜单
  if (parentId.value) {
    formData.parentId = parseInt(parentId.value)
  }

  // 设置页面标题
  const titleMap = {
    add: '新增菜单',
    edit: '编辑菜单',
    view: '查看菜单'
  }
  uni.setNavigationBarTitle({
    title: titleMap[mode.value] || '菜单管理'
  })
})

onMounted(() => {
  // 加载父级菜单选项
  loadParentMenuOptions()

  // 编辑或查看模式，加载数据
  if (mode.value === 'edit' || mode.value === 'view') {
    loadMenuData()
  }

  // 查看模式不需要特殊处理，数据已在loadMenuData中加载
})

// 加载父级菜单选项
async function loadParentMenuOptions() {
  try {
    const response = await listMenu({})
    if (response.code === 200) {
      const menuData = response.data || []
      // 构造树形结构，添加主类目作为根节点
      const treeData = [
        {
          menuId: 0,
          menuName: '主类目',
          children: []
        },
        ...handleTree(menuData, 'menuId', 'parentId', 'children')
      ]
      parentMenuTreeData.value = treeData
    }
  } catch (error) {
    console.error('加载父级菜单失败:', error)
  }
}

// 加载菜单数据
async function loadMenuData() {
  if (!menuId.value) return

  try {
    const response = await getMenu(menuId.value)
    if (response.code === 200) {
      const menuData = response.data
      Object.assign(formData, menuData)
    }
  } catch (error) {
    console.error('加载菜单数据失败:', error)
    proxy.$modal.showToast('加载菜单数据失败')
  }
}

// 提交表单
async function handleSubmit() {
  try {
    const valid = await formRef.value.validate()
    if (!valid) return

    const submitData = {...formData}

    if (mode.value === 'add') {
      const response = await addMenu(submitData)
      if (response.code === 200) {
        proxy.$modal.showToast('新增成功')
        handleBack()
      }
    } else if (mode.value === 'edit') {
      submitData.menuId = menuId.value
      const response = await updateMenu(submitData)
      if (response.code === 200) {
        proxy.$modal.showToast('更新成功')
        handleBack()
      }
    }
  } catch (error) {
    console.error('保存菜单失败:', error)
    proxy.$modal.showToast('保存失败')
  }
}

// 返回上一页
function handleBack() {
  uni.navigateBack()
}

// 颜色选择器相关方法
function openColorPicker() {
  // 如果有当前颜色，转换为RGBA格式
  if (formData.appColor) {
    const color = hexToRgba(formData.appColor)
    colorPickerColor.value = color
  }
  colorPicker.value.open()
}

function onColorConfirm(color) {
  formData.appColor = color.hex
}

function clearColor() {
  formData.appColor = ''
}

// 颜色转换工具函数
function hexToRgba(hex) {
  const result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex)
  return result ? {
    r: parseInt(result[1], 16),
    g: parseInt(result[2], 16),
    b: parseInt(result[3], 16),
    a: 1
  } : {r: 64, g: 158, b: 255, a: 1}
}
</script>

<style lang="scss" scoped>
@import '@/styles/edit-page.scss';

.color-picker-wrapper {
  cursor: pointer;
}

.color-preview {
  width: 20px;
  height: 20px;
  border-radius: 4px;
  border: 1px solid #dcdfe6;
  display: inline-block;
}

.color-preview-large {
  width: 24px;
  height: 24px;
  border-radius: 4px;
  border: 1px solid #dcdfe6;
  display: inline-block;
}
</style> 